﻿using System;
using System.IO;
using System.Net.Http;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;

namespace HanthinkApiTest
{
    public class AspNetCoreUnitTestBase<TStartup>
        where TStartup : class
    {
        //public BaseTest()
        //{
        //    var server = new TestServer(WebHost.CreateDefaultBuilder()
        //        .UseStartup<Startup>());
        //}

        protected AspNetCoreUnitTestBase()
        {
            var builder = CreateWebHostBuilder();
            Server = CreateTestServer(builder);

            Client = Server.CreateClient();

            ServerProvider = Server.Host.Services;
        }

        public TestServer Server { get; }

        public HttpClient Client { get; }

        public IServiceProvider ServerProvider { get; set; }

        protected virtual IWebHostBuilder CreateWebHostBuilder()
        {
            // return new WebHostBuilder().UseStartup<TStartup>();
            return new WebHostBuilder().ConfigureAppConfiguration(builder =>
            {
                builder.SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("appsettings.json");
            }).UseStartup<TStartup>();
        }

        protected virtual TestServer CreateTestServer(IWebHostBuilder builder)
        {
            return new TestServer(builder);
        }
    }
}
